package com.wushi.lenovo.asia5b.app_ui.wish.fragment;

import android.content.Context;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.mvp.base.BaseMvpFragment;
import com.mvp.base.model.ResultModel;
import com.mvp.helper.WCallBack;
import com.mvp.refresh.AutoRefreshLayout;
import com.mvp.refresh.RefreshViewManager;
import com.mvp.ui.view.HeadBar;
import com.mvp.utils.ToastUtil;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_config.WishRepository;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.wish.mvpview.WishFragmentView;
import com.wushi.lenovo.asia5b.app_di.wish.presenter.WishFragmentPresenter;
import com.wushi.lenovo.asia5b.app_event.LoginEvent;
import com.wushi.lenovo.asia5b.app_event.UpdateWisnStateEvent;
import com.wushi.lenovo.asia5b.app_model.other.ShareBean;
import com.wushi.lenovo.asia5b.app_model.wish.WishModel;
import com.wushi.lenovo.asia5b.app_ui.h5.GoodsDetailsActivity;
import com.wushi.lenovo.asia5b.app_ui.other.activity.MainActivity;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.CancelSureDialog;
import com.wushi.lenovo.asia5b.app_ui.other.dialog.ShareDialog;
import com.wushi.lenovo.asia5b.app_ui.wish.activity.WishlistActivity;
import com.wushi.lenovo.asia5b.app_ui.wish.adapter.WishAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import timber.log.Timber;

/**
 * Created by zhangyuncai on 2018/12/14.
 */
public class WishFragment extends BaseMvpFragment<WishFragmentView, WishFragmentPresenter>
        implements WishFragmentView {

    @BindView(R.id.headbar_wishlist)
    HeadBar headbar_wishlist;
    @BindView(R.id.recyclerview_wish)
    RecyclerView mRecyclerView;
    @BindView(R.id.auto)
    AutoRefreshLayout auto;
    private WishAdapter mAdapter;
    private final List<WishModel> mDatas = new ArrayList<>();
    private View emptyView;

    public static WishFragment newInstance(Context context) {
        return (WishFragment) Fragment.instantiate(context, WishFragment.class.getName(), null);
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected int getLayout() {
        return R.layout.fragment_wish;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        EventBus.getDefault().register(this);

        initView();

        initEvent();
        resetView();
    }

    @Override
    protected void lazyFetchData() {

        initData();

    }

    @Override
    protected void initView() {
        if (getActivity() instanceof MainActivity) {
            headbar_wishlist.invisibleBack(View.GONE);
        } else if (getActivity() instanceof WishlistActivity) {
            headbar_wishlist.invisibleBack(View.VISIBLE);
        }
        if (auto != null)
            ((RefreshViewManager) mActivity).addView(auto);
        mAdapter = new WishAdapter(mDatas);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(getContext()));
        mRecyclerView.setAdapter(mAdapter);

        emptyView = View.inflate(getContext(), R.layout.empty_wish, null);
        TextView tv_empty_start = emptyView.findViewById(R.id.tv_empty_start);
        tv_empty_start.setOnClickListener(v -> {
            if (getActivity() instanceof MainActivity) {
                ((MainActivity) getActivity()).setTabCurrenItem(0);
            } else if (getActivity() instanceof WishlistActivity) {
                ((MainActivity) getActivity()).setTabCurrenItem(0);
                getActivity().finish();
            }
        });

    }

    /**
     * 重置界面
     */
    private void resetView() {
        mDatas.clear();
        mAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initData() {
        if (auto != null)
            auto.autoRefresh();
    }

    private void getWishList(int refresh) {
        getPresenter().getWishList(refresh);
    }


    @Override
    protected void initEvent() {
        if (auto != null)
            auto.setOnRefreshListener(refreshLayout -> {
                getWishList(1);
            });
        if (auto != null)
            auto.setOnLoadMoreListener(refreshLayout -> {
                getWishList(2);
            });
        mAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                WishModel wishModel = mAdapter.getItem(position);
                switch (view.getId()) {
                    case R.id.ll_wish_delete:
                        new CancelSureDialog(getContext(), R.string.yes, R.string.no, R.string.wish_deletenotice, new WCallBack() {
                            @Override
                            public void callback(Object o) {
                                getPresenter().deleteWish(wishModel.getProduct_id());
                            }
                        }).show();
                        break;
                    case R.id.iv_wish_share:
                        if (!TextUtils.isEmpty(wishModel.getAlternative_url())) {
                            ShareBean shareBean = new ShareBean();
                            shareBean.setShareUrl(wishModel.getAlternative_url());
                            shareBean.setDesc(wishModel.getProduct_name());
                            shareBean.setTitle(wishModel.getProduct_name());
                            shareBean.setImgUrl(wishModel.getImage());
                            ShareDialog shareDialog = new ShareDialog(getActivity(), shareBean);
                            shareDialog.show();
                        }
                        break;
                    case R.id.iv_wish_shopcar:
                        GoodsDetailsActivity.startGoodsDetailsActivity(getContext(), wishModel.getProduct_id());
                        break;
                    default:
                        break;
                }
            }
        });
    }


    @Override
    public void getWishListResult(List<WishModel> wishModels, int page, int sumPage, int total) {
        if (page == 1) {
            mDatas.clear();
        }
        if (wishModels != null) {
            mDatas.addAll(wishModels);
        }
        mAdapter.notifyDataSetChanged();
        if (page == sumPage || mDatas.size() == 0) {
            if (auto != null)
                auto.setEnableLoadMore(false);
        } else {
            if (auto != null)
                auto.setEnableLoadMore(true);
        }
        if (mDatas.size() == 0) {
            mAdapter.setEmptyView(emptyView);
        }
        WishRepository.updateWishCount();
    }


    @Override
    public void deleteWishResult(ResultModel resultModel, int prod_id) {
        if (resultModel.isSuccess()) {
            ToastUtil.showToast(resultModel.getMsg());
            int i = 0;
            for (WishModel wishModel : mDatas) {
                if (wishModel.getProduct_id() == prod_id) {
                    mDatas.remove(i);
                    mAdapter.notifyItemRemoved(i);
                    break;
                }
                i++;
            }
        }
        if (mDatas.size() == 0) {
            mAdapter.setEmptyView(emptyView);
        }

        WishRepository.updateWishCount();
    }

    @Override
    public void dismissLoadingBar(Object dississTag) {
        super.dismissLoadingBar(dississTag);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Override
    public void showLoadingFailureError(Throwable throwable) {
        super.showLoadingFailureError(throwable);
        if (auto != null) {
            auto.finishRefreshAndLoadmore();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onLoginEvent(LoginEvent event) {
        if (event != null) {

            if (TextUtils.equals(event.loginState, CommonConstant.LOGIN_SUCCESS)) {
                Timber.d("--->>>>>>>>---登录成功");
//                    getWishList(1);
            } else if (TextUtils.equals(event.loginState, CommonConstant.LOGOUT_SUCCESS)) {
                hasFetchData = false;
                resetView();
            }

        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onUpdateWishEvent(UpdateWisnStateEvent event) {
        if (event != null) {
            getWishList(1);

        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        EventBus.getDefault().unregister(this);
    }
}